package com.cysion.study.ui

import android.content.Context
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.other.color
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.uibox.dialog.CONFIRM
import com.cysion.study.R
import com.cysion.study.entity.CreateOrderEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.presenter.RecharPresenter
import com.cysion.study.ui.iview.RecharView
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.http.HttpUtil
import com.cysion.study.widget.pay.PaymentHelper
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import kotlinx.android.synthetic.main.activity_rechar.*
import org.json.JSONObject

//充值
class RecharActivity : BaseActivity(), View.OnClickListener, RecharView {
    override fun setUserInfo(u: CreateOrderEntity) {
        CLog.i("订单信息2=${u}")
    }

    override fun loading() {
    }

    override fun stopLoad() {
    }

    override fun error(code: Int, msg: String) {
        CLog.i("订单信息3=$msg")
    }

    val presenter by lazy {
        RecharPresenter().apply {
            attach(this@RecharActivity)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_rechar

    override fun initView() {
        whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("充值")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }

        tvNext.setOnClickListener(this)

    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvNext -> {//充值
                hidekey()
                var money = et_content.textEx.toString().trim()
                et_content.checkBlank("请输入充值金额") ?: return
                Alert.payType(self,"","","","确定"){confirm, type->
                    if (TextUtils.isEmpty(type)) {
                        ShowToast("请选择支付方式")
                        return@payType
                    }
                    if (confirm == CONFIRM) {
                        //1支付宝  2微信
                        if (type == "1") {
                            submit(money)
                        }else if (type == "2") {
                            ShowToast("微信支付")
                        }
                    }
                }
            }
        }
    }

    fun hidekey() {
        val im = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val v = this.currentFocus
        im.hideSoftInputFromWindow(v.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    private fun submit(money: String) {
        Alert.loading(self)
        ApiClient.api.recharge(UserCache.token, money).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    //RechargeEntity
                    var orderId = it.id
                    createOrder(orderId)
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private fun createOrder(orderId: String) {
        Alert.loading(self)
        val params = RequestParams()
        params.put("token", UserCache.token)
        params.put("orderId", orderId)
        var url=Urls.HOST+"/education/teacher/app/alipay/createOrder"
        HttpUtil.post1(url, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out org.apache.http.Header>?, response: JSONObject?) {
                super.onSuccess(statusCode, headers, response)
                Alert.close()
                try {
//                    showToastMsg(response.getString("errorDescription"))
                    if (response?.getString("code") == "0") {
                        CLog.i("订单信息2=${response.getString("data")}")
                        PaymentHelper(self, PaymentHelper.PayCallBack {
                            CLog.i("支付信息=$it")
                            if (it == "9000") {
                                ShowToast("支付成功")
                                finish()
                            }else if (it == "6001") {
                                ShowToast("取消支付")
                            }else {
                                ShowToast("支付失败")
                            }
                        }).startAliPay(response.getString("data"))
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
//                    ShowDialog.dissmiss()
                }
            }


            override fun onFinish() {
                Alert.close()
            }

            override fun onFailure(statusCode: Int, headers: Array<out org.apache.http.Header>?, responseString: String?, throwable: Throwable?) {
                super.onFailure(statusCode, headers, responseString, throwable)
                Alert.close()
            }
        })

    }


    override fun closeMvp() {
    }

}
